package com.hdd.hll.quartz.job;

import com.alibaba.fastjson.JSON;
import com.hdd.hll.common.response.Result;
import com.hdd.hll.common.utils.AesEncryptUtils;
import com.hdd.hll.common.utils.OpenApiLogUtil;
import com.hdd.hll.modules.customer.web.dto.CustomerDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * 客户推送Job实现类
 *
 * @author jw
 */
@Slf4j
@Component
public class PushCustomerJob implements Job {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${jd.api.url}")
    private String apiUrl;

    @Value("${api.path.suffix.mcustomer}")
    private String mCustomer;

    @Override
    public void execute(JobExecutionContext context) {
        Map map = context.getJobDetail().getJobDataMap();
        Set<Map.Entry<String, String>> entrys = map.entrySet();
        for (Map.Entry<String, String> entry : entrys) {
            // 渠道参数，执行相应的业务流程
            log.info("执行JD客户主数据接口推送任务，入参：{}", entry.getValue());
            getCustomerOpsResponse(JSON.parseObject(entry.getValue(), CustomerDto.class), mCustomer);
        }
    }

    private Result<String> getCustomerOpsResponse(CustomerDto customerDto, String customerOpsPath) {
        StringBuilder dataValidResult = paramValid(customerDto);
        Result<String> result = new Result<>();
        if (StringUtils.isNotBlank(dataValidResult)) {
            result.setCode("301");
            result.setMsg(dataValidResult.toString());
            OpenApiLogUtil.logResponse(result);
            return result;
        }
        Result<String> decryptResp = null;

        try {
            String encryptJsonString = restTemplate.postForObject(apiUrl + customerOpsPath, AesEncryptUtils.encrypt(JSON.toJSONString(customerDto)), String.class);
            decryptResp = JSON.parseObject(AesEncryptUtils.decrypt(encryptJsonString), Result.class);

            log.info("JOB请求JD客户主数据接口，Msg：{}", decryptResp);
        } catch (Exception e) {
            log.error("请求JD客户主数据接口异常，Msg：{}", e.getMessage());
            if (Objects.isNull(decryptResp)) {
                decryptResp = new Result<>();
            }
            decryptResp.setCode("500");
            decryptResp.setMsg(String.format("JOB请求JD客户主数据接口异常，Msg：%s", e.getMessage()));
        }

        OpenApiLogUtil.logResponse(decryptResp);
        return decryptResp;
    }

    private StringBuilder paramValid(CustomerDto customerDto) {
        StringBuilder dataValidResult = new StringBuilder();
        if (StringUtils.isBlank(customerDto.getMiningDistrictId())) {
            dataValidResult.append("获取矿区编码异常：miningDistrictId must not be null or empty!");
        }
        if (StringUtils.isBlank(customerDto.getMiningDistrict())) {
            dataValidResult.append("获取矿区名称异常：miningDistrict must not be null or empty!");
        }
        if (StringUtils.isBlank(customerDto.getCustomerId())) {
            dataValidResult.append("获取客户编码异常：customerId must not be null or empty!");
        }
        if (StringUtils.isBlank(customerDto.getCustomerName())) {
            dataValidResult.append("获取客户名称异常：customerName must not be null or empty!");
        }
        return dataValidResult;
    }
}
